#!/bin/sh

# Config
: "${RSYNCPTH:="rsync://distfiles.master.finkmirrors.net/distfiles/"}"
FIROOT="/Volumes/src2/fink/distfiles"
LOCKFILE="/var/run/fink-dist-rsync.lock"

usage() {
	cat > "/dev/stderr" << EOF
usage: ${0} [ -l <lockfile> ] [ -o <outputdir> ]
Defaults:
	outputdir: ${FIROOT}
	lockfile: ${LOCKFILE}
EOF
	exit 1
}

while getopts ":l:o:" OPTION; do
	case "${OPTION}" in
		l)
			LOCKFILE="${OPTARG}"
		;;
		o)
			FIROOT="${OPTARG}"
		;;
		?)
			usage
		;;
	esac
done

# Prevent more than one concurrent update
lockfile -r "0" -l "28800" "${LOCKFILE}" || exit 0

# Make the directories if they do not already exist
if [ ! -d "${FIROOT}/distfiles" ]; then
	mkdir -p "${FIROOT}/distfiles"
fi

if [ ! -d "${FIROOT}/distfiles.tmp" ]; then
	mkdir -p "${FIROOT}/distfiles.tmp"
fi

cd "${FIROOT}"

# Note the start time of a new fetch
date -u +%s > "${FIROOT}/distfiles/UPDATE"

# Update from rsync with a 10 min timeout
if ! rsync -aq --timeout=600 --delete-after --exclude="TIMESTAMP" --exclude="LOCAL" --exclude="UPDATE" --partial-dir="${FIROOT}/distfiles.tmp/" "${RSYNCPTH}" "${FIROOT}/distfiles/"; then
	rm -f "${LOCKFILE}"
	exit 1
fi

# Fetch the timestamp file
if ! rsync -azq --timeout=60 --delete-after "${RSYNCPTH}TIMESTAMP" "${FIROOT}/distfiles/TIMESTAMP"; then
	rm -f "${LOCKFILE}"
	exit 1
fi

# Add the local timestamp
date -u +%s > "${FIROOT}/distfiles/LOCAL"


# Clean up
rm -f "${LOCKFILE}"

exit 0

